package com.gk.javaservice.util.DownLoadManager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class FileDownloader {

    public static Boolean saveFileDownNoSSL(String urlStr, String filePath, String fileName, String method) {
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        try {
            // 为当前连接创建不验证SSL的上下文，避免影响全局设置
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, getInsecureTrustManager(), new java.security.SecureRandom());

            HttpURLConnection connection = setupConnection(urlStr, sc, method);

            InputStream inputStream = connection.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);

            if (!filePath.endsWith("/")) {
                filePath += "/";
            }
            FileOutputStream fileOut = new FileOutputStream(filePath + fileName);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);
            byte[] buf = new byte[4096];
            int length;
            while ((length = bis.read(buf)) != -1) {
                bos.write(buf, 0, length);
            }
            bos.close();
            bis.close();
            return true;
        } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
            return false;
        }
    }

    private static TrustManager[] getInsecureTrustManager() {
        return new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                }
        };
    }

    private static HttpURLConnection setupConnection(String urlStr, SSLContext sc, String method) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection connection;
        if ("https".equalsIgnoreCase(url.getProtocol())) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
            httpsConnection.setSSLSocketFactory(sc.getSocketFactory());
            httpsConnection.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true; // 忽略主机名验证
                }
            });
            connection = httpsConnection;
        } else {
            connection = (HttpURLConnection) url.openConnection();
        }
        connection.setRequestMethod(method);
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        return connection;
    }
}
